﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Microsoft.Windows.Controls.Ribbon;
using System.Windows.Input;

namespace Southridge.View
{

    
    public class RibbonTabSelectedBehavior
    {

        public static void SetSelectionChanged(DependencyObject depObj, object value)
        {
            depObj.SetValue(RibbonTabSelectedBehavior.SelectionChangedProperty , value);
        }


        public static DependencyProperty SelectionChangedProperty =
                DependencyProperty.RegisterAttached("SelectionChanged",
                typeof(object),
                typeof(RibbonTabSelectedBehavior),
                new UIPropertyMetadata(RibbonTabSelectedBehavior.TabSelectedChanged));



        private static void TabSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            RibbonTab rt = depObj as RibbonTab; 
             
            //This just subscribers OUR handler...  
            // Notice we are NOT caching the command, it gets retrieved on demand when OnSelected is fired.. 

            if (rt == null) throw new ArgumentException ("depObj");
            if ((e.NewValue != null) && (e.OldValue == null))
            {
                rt.Selected += OnSelected;
            }
            else if ((e.NewValue == null) && (e.OldValue != null))
            {
                rt.Selected -= OnSelected;
            }
        }

        private static void OnSelected (object sender, RoutedEventArgs  e)
        {
            RibbonTab rt = sender as RibbonTab;
            System.Diagnostics.Debug.Assert(rt != null);
            ICommand command = rt.GetValue(RibbonTabSelectedBehavior.SelectionChangedProperty) as ICommand;
            if (command != null)
            {
                command.Execute(e);
            }
        }
    }
}
